'use strict';
const db = uniCloud.database();
const collection = db.collection('zhihu-daily-articles')
exports.main = async ({type}, context) => {
	
	// //获取已存库的最大文章ID
	let maxIdInDb = await getMaxTime();
	console.log('maxIdInDb',maxIdInDb);
	// // 开始抓取首页链接
	var indexArr = []
	
	let ctime
	let apiUrl='http://api.tianapi.com/topnews/index'
	const res = await uniCloud.httpclient.request(apiUrl, {
	    method: 'GET',
	    data: {
	      key: '1a162a6b0fec66a258dc8f80a8c9cfdb',
		  num:15
	    },
	    contentType: 'json', // 指定以application/json发送data内的数据
	    dataType: 'json' // 指定返回值为json格式，自动进行parse
	  })
	console.log(res.data)
	if(res.status==200 && res.data &&res.data.newslist.length>0){
		let list=res.data.newslist
		for (let i = 0; i < list.length; i++) {
			 let _time= list[i].ctime
			 
			 if(new Date(_time)> new Date(maxIdInDb)){
				 indexArr.push(list[i])
			 }
		}
		console.log('新增文章数量：',indexArr.length);
		
		if(indexArr.length>0){
			for (let i = 0; i < indexArr.length; i++) {
				
				saveArticle(indexArr[i])
			}
		}
	}
	
	return indexArr
};

async function getMaxTime(){
  // 获取已存库的最大文章ID
  const record = await collection.field({
    zhihu_id: true
  }).orderBy("zhihu_id", "desc").limit(1).get()

  let maxIdInDb = 0
  if (record && record.data && record.data.length > 0) {
    maxIdInDb = record.data[0].zhihu_id
  }
  return maxIdInDb
}

async function saveArticle(article) {
	// console.log(article);
	let articles = {
	  zhihu_id: article.ctime,
	  ...article
	}
  
  const addRes = await collection.add(articles)
  if (addRes.id || addRes.affectedDocs === 1) {
    console.log( " -> 添加成功");
  }

}